package com.test.wog.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.springframework.stereotype.Component;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Map;

/**
 * 调用WEB API
 *
 * @author LX
 * @since 2020-01-30
 */
@Component
public class HttpRequestUtil {
    public JSONObject getJSONFromWebAPI(String url, Map<String, String> param){
        /*URL拼接参数*/
        String urlWithParam = new String(url);
        boolean isFirst = true;
        for (Map.Entry<String, String> entry : param.entrySet()) {
            String temp = entry.getKey() + "=" + entry.getValue();
            if(isFirst){
                urlWithParam += "?" + temp;
            }
            else{
                urlWithParam += "&" + temp;
            }
            isFirst = false;
        }
        /*URL获取json字符串*/
        System.out.println(urlWithParam);
        StringBuilder json = new StringBuilder();
        try {
            URL urlObject = new URL(urlWithParam);
            URLConnection uc = urlObject.openConnection();
            uc.connect();
            BufferedReader in = new BufferedReader(new InputStreamReader(uc.getInputStream(),"UTF-8"));
            String inputLine = null;
            while ( (inputLine = in.readLine()) != null) {
                json.append(inputLine);
            }
            in.close();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            return null;
        }
        /*json字符串转对象*/
        return JSON.parseObject(String.valueOf(json));
    }
}
